package gzhaoku.com.common;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import gzhaoku.com.common.ui.annotations.Layout;
import gzhaoku.com.common.ui.annotations.Widget;
import gzhaoku.com.common.ui.annotations.WidgetClick;
import gzhaoku.com.machinemain.jssdk.SDK;

public abstract class BaseActivity extends Activity {

    private static Logger log = Logger.getLog(BaseActivity.class);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initLayout();
        initView();
        initListener();

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                String[] PERMISSIONS_STORAGE = {
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE };
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, 1);
            }else{
                onActivityCreate(savedInstanceState);
            }
        }else{
            onActivityCreate(savedInstanceState);
        }

    }



    void initListener() {
        final Activity that = this;
        for(final Method m: this.getClass().getDeclaredMethods()){
            WidgetClick wc = m.getAnnotation(WidgetClick.class);
            if(wc != null){
                View v = this.findViewById(wc.id());
                if(v != null){
                    v.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            try {
                                m.invoke(that, v);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        }
    }

    void initView(){
        for( Field f: this.getClass().getDeclaredFields()){
            Widget ir = f.getAnnotation(Widget.class);
            if(ir != null){
                try {
                    f.setAccessible(true);
                    View v = this.findViewById(ir.id());
                    if(v == null){
                        log.w("Failed to inject view: %d => %s", ir.id(), f);
                    }
                    log.i("Inject view: %s", f.getName());
                    f.set(this, v);
                } catch (Exception e) {
                    log.e(e, "Failed to inject view to %s", f);
                }
            }
        }
    }

    void initLayout(){
        Layout il = this.getClass().getAnnotation(Layout.class);
        if(il != null){

            if(il.fullscreen()){
                fullscreen();
            }

            if(il.content() > 0){
                setContentView(il.content());
            }



            //TODO 处理其他的Layout https://gitee.com/steven0lisa/typhoon-forecast-app/blob/master/src/net/jingkao/app/common/UIHelper.java
        }
    }

    void fullscreen(){
        //去除标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //去除状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
//            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
//                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
//                    | View.SYSTEM_UI_FLAG_FULLSCREEN;
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav
                    // bar
//                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(uiOptions);
        }

    }

    public void showLongToast(String message){
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    public void showShortToast( String message){
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    protected void showActivity(Class<? extends Activity> clazz, boolean finish){
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
        if(finish)
            this.finish();
    }

    @Override
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
        switch (config.orientation) {
            case Configuration.ORIENTATION_LANDSCAPE:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            onActivityCreate(null);
        }

    }

    protected void onActivityCreate(Bundle savedInstanceState){

    }
}
